package com.liuyi.netty.im.lychat.modular.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuyi.netty.im.commons.codes.data.event.Message;
import com.liuyi.netty.im.commons.codes.data.event.message.playload.Playload;
import com.liuyi.netty.im.lychat.LychatConst;
import com.liuyi.netty.im.lychat.config.base.BaseController;
import com.liuyi.netty.im.lychat.modular.controller.model.MessageUserRecordsModel;
import com.liuyi.netty.im.lychat.modular.controller.model.MessageUserRecordsModel.CreateMessage;
import com.liuyi.netty.im.lychat.modular.controller.model.MessageUserRecordsModel.SendMessage;
import com.liuyi.netty.im.lychat.modular.entity.MessageRecords;
import com.liuyi.netty.im.lychat.modular.entity.MessageUserRecords;
import com.liuyi.netty.im.lychat.modular.enums.SessionType;
import com.liuyi.netty.im.lychat.modular.service.IMessageUserRecordsService;
import com.liuyi.netty.im.server.util.ImHelp;
import com.liuyi.rapid.develop.tool.resp.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

import static com.liuyi.rapid.develop.tool.resp.ResponseCall.success;
import static com.liuyi.rapid.develop.tool.resp.ResponseCall.successMsg;
import static org.springframework.http.ResponseEntity.ok;

/**
 * <p>
 * 消息用户记录表 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-12-29
 */
@Api(value = "", tags = {"消息用户记录表"})
@RestController
@RequestMapping("/modular/message-user-records")
@Validated
public class MessageUserRecordsController implements BaseController<MessageUserRecords, IMessageUserRecordsService> {

    @Resource
    private IMessageUserRecordsService messageUserRecordsService;

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "sessionId", value = "会话id"),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "messageId", value = "最上一条消息，可以不填")
    })
    @ApiOperation(value = "消息拉取", notes = "", httpMethod = "GET")
    @GetMapping("/list/{sessionId}")
    public ResponseEntity<Response<MessageUserRecordsModel.ResultList>> list(@PathVariable String sessionId, String messageId) {
        MessageUserRecordsModel.ResultList resultList = new MessageUserRecordsModel.ResultList();
        QueryWrapper<MessageUserRecords> queryWrapper = q().eq(MessageUserRecords.USER_ID, StpUtil.getLoginIdAsString())
                .eq(MessageUserRecords.SESSION_ID, sessionId)
                .lt(StrUtil.isNotEmpty(messageId), MessageUserRecords.MESSAGE_ID, messageId)
                .orderByDesc(MessageUserRecords.ID);
        int count = server().count(queryWrapper);
        if (count <= 15) {
            resultList.setFinished(true);
        }
        List<MessageUserRecords> userRecords = server().list(queryWrapper.last("limit 15"));
        resultList.setMessages(server().wrapperMessage(CollUtil.reverse(userRecords)));
        return ok(success(resultList));
    }

    @ApiOperation(value = "发送消息", notes = "", httpMethod = "POST")
    @PostMapping("/sendMessage")
    public ResponseEntity<Response<Void>> sendMessage(@Valid @RequestBody SendMessage p) {
        server().sendMessage(p.getMessageId());
        return ok(successMsg("发送成功"));
    }

    @ApiOperation(value = "创建消息", notes = "返回消息id", httpMethod = "POST")
    @PostMapping("/createMessage")
    public ResponseEntity<Response<Message<? extends Playload>>> createMessage(@Valid @RequestBody CreateMessage p) {
        String sessionId = p.getSessionId();
        String toId = ImHelp.sessionIdToId(sessionId);
        SessionType sessionType = LychatConst.getSessionType(sessionId);
        MessageRecords message = messageUserRecordsService.createMessage(StpUtil.getLoginIdAsString(), toId, sessionType, p.getContentType(), p.getContent());
        return ok(success(server().wrapper(message, StpUtil.getLoginIdAsString(), p.getSessionId())));
    }

    @Override
    public IMessageUserRecordsService server() {
        return messageUserRecordsService;
    }
}

